package com.klasster.recruitmentPlatform.common.util;

import cn.hutool.core.bean.BeanUtil;
import com.klasster.recruitmentPlatform.domain.po.Permission;
import com.klasster.recruitmentPlatform.domain.vo.PermissionVO;
import com.klasster.recruitmentPlatform.service.impl.PermissionServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

@Component
@RequiredArgsConstructor
public class PermissionUtil {

    private final PermissionServiceImpl permissionService;

    public List<PermissionVO> getPermissions(String role) {
        List<Permission> permissions = permissionService.getByRole(role);
        List<PermissionVO> permissionVOs = BeanUtil.copyToList(permissions,PermissionVO.class);
        HashMap<String, PermissionVO> map = new HashMap<>();
        permissionVOs.forEach(p -> {map.put(p.getCode(),p);});
        permissions.forEach(p -> {
            if(!p.getParent_code().isBlank()) {
                PermissionVO parent = map.get(p.getParent_code());
                PermissionVO child = map.get(p.getCode());
                parent.addChildren(child);
                map.remove(p.getCode());
            }
        });
        permissionVOs.clear();
        permissionVOs.addAll(map.values());
        return permissionVOs;
    }

}
